package org.apache.myfaces.blank.tm.frokjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author JsD
 * @ClassName ForkJoinWorkDemo.java
 * @Description
 * @createTime 2021年06月04日 10:24:00
 */
public class ForkJoinWorkDemo extends RecursiveTask<Long> {

    private long start;
    private long end;

    //临界点
    private static final long THRESHOLD = 1_0000L;

    public ForkJoinWorkDemo(long start,long end){
        this.start =start;
        this.end=end;
    }

    @Override
    protected Long compute() {
        long len = end - start;
        if (len <THRESHOLD){
//            直接循环累加
            long sum=0L;
            for (long i = start; i < end; i++) {
                sum = sum +i;
            }
            return sum;
        }else {
//超过临界值,进行任务拆分
            Long mid=(start+end)/2;
            ForkJoinWorkDemo left=new ForkJoinWorkDemo(start,mid);
            ForkJoinWorkDemo right=new ForkJoinWorkDemo(mid+1,end);
            left.fork();
            right.fork();
            return left.join()+ right.join();
        }

    }
}
